<?php


namespace App\Service\RiskCheck;

use App\Constants\XZXResponseCode;
use App\Model\Dao\RiskRuleMchRefDao;
use App\Model\Dao\RiskRuleWhitetextConnDao;
use App\Model\Dao\RiskRuleWhitetextParamDao;
use App\Model\Enum\RiskRuleMchRefTypeEnum;
use App\Model\Enum\RiskRuleWhiteParamTypeEnum;
use App\Utils\CustomUtils;
use App\Utils\RiskCheckUtils;
use Hyperf\Database\Query\Builder;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Arr;/**
 * Class MchWhiteRiskCheckService
 * 商户白名单风控
 *
 * @package App\Service\RiskCheck
 */
class MchWhiteRiskCheckService implements RiskCheckInterface {

    /**
     * @Inject()
     * @var RiskRuleMchRefDao
     */
    protected $RiskRuleMchRefDao;

    public function handle ($params) {

        $mchNo = Arr::get($params, "mchNo");

        $ruleList = $this->RiskRuleMchRefDao->readMchWhiteRuleList($mchNo);

        CustomUtils::xzxDebug("商户白名单规则列表", $ruleList);

        foreach ($ruleList as $rule) {
            $re = $this->_check($params, $rule);

            if ($re['code'] != XZXResponseCode::SUCCESS_CODE) {
                return CustomUtils::xzxResponseData($re['code'], $re['message'], $re['data']);
            }
        }

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE);
    }

    protected function _check ($params, $rule) {

        $paramName     = $rule['whiteTextName'];
        $ruleType      = $rule['whiteType'];
        $contrastValue = $rule['whiteText'];

        if (Arr::exists($params, $paramName)) {
            // 指定参数存在, 检查规则是否匹配
            $checkValue = $params[$paramName];

            $bool = false;
            if ($ruleType == RiskRuleWhiteParamTypeEnum::CARD_NO) {
                $bool = RiskCheckUtils::inHandle(substr($checkValue, 0, 6), $contrastValue);
            }
            else {
                $bool = RiskCheckUtils::inHandle($checkValue, $contrastValue);
            }

            if (!$bool) {

                $data = [
                    'ruleId'               => $rule['id'],
                    'collectionId'         => $rule['collectionId'],
                    'collectionName'       => $rule['collectionName'],
                    'whiteTextDisplayName' => $rule['whiteTextDisplayName'],
                    'whiteTextName'        => $rule['whiteTextName'],
                ];

                $msg = trans('dispatch.check.whitelist.not_match', [
                    'param' => RiskRuleWhiteParamTypeEnum::getLabel($ruleType),
                ]);

                return CustomUtils::xzxResponseData(XZXResponseCode::FAILED_CODE, $msg, $data);
            }

        }

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE);
    }

    /**
     * 刷新商户白名单缓存
     *
     * @param $mchNo
     */
    public function clearCache ($mchNo) {
        $this->RiskRuleMchRefDao->clearMchWhiteRuleList($mchNo);
    }

}
